package com.example.uCenter.user.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.uCenter.common.Code;
import com.example.uCenter.common.Result;
import com.example.uCenter.common.SendCode;
import com.example.uCenter.user.entity.Information;
import com.example.uCenter.user.mapper.InformationMapper;
import com.example.uCenter.user.service.IInformationService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 服务实现类
 *
 * @author yzh
 * @since 2022-08-29
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements IInformationService {

    // private ThreadLocal<String> local = new ThreadLocal<>();
    private String local = "";

    @Override
    public List<Information> selectAllByInformation() {
        return getBaseMapper().selectList(null);
    }

    /**
     * 新增
     *
     * @param information
     * @return
     */
    @Override
    public boolean RegisterByInformationAdd(Information information) {
        // begin
        boolean isSuccess = false;
        int insert = getBaseMapper().insert(information);
        if (insert == 1) {
            isSuccess = true;
        }
        // end
        return isSuccess;
    }

    /**
     * 查询电话号码是否存在
     *
     * @param phoneNum
     * @return
     */
    @Override
    public Result findPhoneNum(String phoneNum) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("phone_num", phoneNum);
        Information information = getBaseMapper().selectOne(qw);
        Result result = new Result(false, Code.GET_ERROR, "查询失败");
        if (Objects.nonNull(information)) {
            SendCode sendCode = new SendCode();
            String code = sendCode.findSendCode(phoneNum);
            local = code;
            result.setData(information);
            result.setCode(Code.GET_OK);
            result.setMsg("查询成功");
        }
        return result;
    }

    /**
     * 通过电话号码发送验证码
     *
     * @param phoneNum
     * @param smsCode
     * @return
     */
    @Override
    public Result sendCode(String phoneNum, String smsCode) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("phone_num", phoneNum);
        Information information = getBaseMapper().selectOne(qw);
        Result result = new Result(false, Code.GET_ERROR, "查询失败");
        String code = local;
        if (Objects.nonNull(information) && smsCode.equals(code)) {
            result.setData(smsCode);
            result.setCode(Code.GET_OK);
            result.setMsg("验证成功");
        }
        return result;
    }
}